package com.rf.richfitwheel.outbill.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rf.richfitwheel.admin.sys.vo.UserVO;
import com.rf.richfitwheel.admin.utils.UserUtil;
import com.rf.richfitwheel.common.enums.ResultStatus;
import com.rf.richfitwheel.common.exception.BusinessException;
import com.rf.richfitwheel.common.exception.ResultException;
import com.rf.richfitwheel.common.utils.R;
import com.rf.richfitwheel.common.utils.StringUtils;
import com.rf.richfitwheel.outbill.feignclient.FWfTaskService;
import com.rf.richfitwheel.outbill.model.AcceptBillInfo;
import com.rf.richfitwheel.outbill.model.OutBillInfo;
import com.rf.richfitwheel.outbill.model.ReceiptBillInfo;
import com.rf.richfitwheel.outbill.dao.ReceiptBillInfoMapper;
import com.rf.richfitwheel.outbill.param.ReceiptBillInfoParam;
import com.rf.richfitwheel.outbill.service.ReceiptBillInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rf.richfitwheel.utils.PageJson;
import com.rf.richfitwheel.workflow.conf.WorkflowContants;
import com.rf.richfitwheel.workflow.entity.WfTaskParam;
import net.sf.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lihong
 * @since 2024-06-19
 */
@Service
public class ReceiptBillInfoServiceImpl extends ServiceImpl<ReceiptBillInfoMapper, ReceiptBillInfo> implements ReceiptBillInfoService {

    @Autowired
    private ReceiptBillInfoMapper receiptBillInfoMapper;

    @Autowired
    private FWfTaskService fWfTaskService;

    @Override
    public PageJson pageJson(ReceiptBillInfoParam receiptBillInfo) {
        Page<ReceiptBillInfo> page = new Page<>(receiptBillInfo.getPageNum(), receiptBillInfo.getPageSize());
        QueryWrapper<ReceiptBillInfo> queryWrapper = new QueryWrapper<>();
        //票据类型
        if (StringUtils.isNotBlank(receiptBillInfo.getOutBillType())) {
            queryWrapper.eq("out_bill_type", receiptBillInfo.getOutBillType());
        }
        //收款全称
        if (StringUtils.isNotBlank(receiptBillInfo.getReceiptBillFullname())) {
            queryWrapper.like("receipt_bill_fullname", receiptBillInfo.getReceiptBillFullname());
        }
        //票据金额
        if (receiptBillInfo.getAmtList().size() == 2 && (receiptBillInfo.getAmtList().get(0) != null)) {
            queryWrapper.between("bill_amount", receiptBillInfo.getAmtList().get(0), receiptBillInfo.getAmtList().get(1));
        }

        //出票日期
        if (StringUtils.isNotBlank(receiptBillInfo.getDateList())) {
            if (receiptBillInfo.getDateList().size() == 2 && (!receiptBillInfo.getDateList().get(0).isEmpty())) {
                queryWrapper.between("out_bill_start", DateUtil.parse(receiptBillInfo.getDateList().get(0), "yyyy-MM-dd"),
                        DateUtil.parse(receiptBillInfo.getDateList().get(1), "yyyy-MM-dd"));
            }
        }
        //单据状态
        if (StringUtils.isNotBlank(receiptBillInfo.getApvst())) {
            queryWrapper.eq("apvst", receiptBillInfo.getApvst());
        }
        //指令状态
        if (StringUtils.isNotBlank(receiptBillInfo.getInstructionStatus())) {
            queryWrapper.eq("instruction_status", receiptBillInfo.getInstructionStatus());
        }
        queryWrapper.orderByDesc("update_time");
        Page<ReceiptBillInfo> pageData = receiptBillInfoMapper.selectPage(page, queryWrapper);
        return PageJson.of(pageData);
    }

    @Override
    public boolean addFlow(Map<String, Object> params) {
        //1.人工登記
        UserVO user = UserUtil.getUser();
        ReceiptBillInfo receiptBillInfo = JSONUtil.toBean(JSONUtil.parseObj(params.get("receiptBillInfo")), ReceiptBillInfo.class);
        receiptBillInfo.setApvst("2");
        receiptBillInfo.setCreateName(user.getStaffName());
        receiptBillInfo.setUpdateName(user.getStaffName());

        if (StringUtils.isNotBlank(receiptBillInfo.getId())) {
            receiptBillInfoMapper.updateById(receiptBillInfo);
        } else {
            receiptBillInfoMapper.insert(receiptBillInfo);
        }
        WfTaskParam wfTaskParam = (WfTaskParam) JSONObject.toBean(JSONObject.fromObject(params.get("wfTaskParam")), WfTaskParam.class);
        wfTaskParam.setUserVO(user);
        wfTaskParam.setProcessInsName(user.getDefaultOrg().getParentOrg().getOrgName() + "出票登记");
        wfTaskParam.setBusinessKey(receiptBillInfo.getId());//业务主键
        wfTaskParam.setApproveNo(receiptBillInfo.getOutBillNumber());//审批编号
        Map<String, Object> variables = wfTaskParam.getBaseParam(user);//组装流程参数
        variables.put("userId",user.getId());
        variables.put("userStaffName",user.getStaffName());
        variables.put("userOrgCode",user.getDefaultOrg().getOrgCode());
        wfTaskParam.setVariables(variables);
        R r = fWfTaskService.submitTask(wfTaskParam);
        if (!"0".equals(r.get("code").toString())) {
            throw new BusinessException(r.get("msg").toString());
        }
        return true;
    }

    @Override
    public void updateReceiptBill(String id, String status, String processInstanceId) {
        QueryWrapper<ReceiptBillInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        ReceiptBillInfo receiptBillInfo = receiptBillInfoMapper.selectOne(queryWrapper);
        if (status.equals(WorkflowContants.PROCESS_STATUS_1)) {
            receiptBillInfo.setProcessInstanceId(processInstanceId);
            receiptBillInfo.setApvst("3");
            receiptBillInfoMapper.updateById(receiptBillInfo);
        }
        //这里判断是否是开票登记的流程结束
        if (status.equals(WorkflowContants.PROCESS_STATUS_2)) {
            //4本部审批结束
            receiptBillInfo.setApvst("4");
            receiptBillInfoMapper.updateById(receiptBillInfo);
        }
        if (status.equals(WorkflowContants.PROCESS_STATUS_3)) {
            receiptBillInfo.setApvst("6");
            receiptBillInfoMapper.updateById(receiptBillInfo);
        }
    }

    @Override
    public boolean modifyFlow(Map<String, Object> params, UserVO user) {
        ReceiptBillInfo receiptBillInfo = JSONUtil.toBean(JSONUtil.parseObj(params.get("receiptBillInfo")), ReceiptBillInfo.class);
        if (receiptBillInfo.getId() == null || "".equals(receiptBillInfo.getId())) {
            throw new ResultException(ResultStatus.FAILURE, "获取id失败，id不能为空！");
        }
        receiptBillInfo.setUpdateName(user.getStaffName());
        receiptBillInfoMapper.updateById(receiptBillInfo);
        WfTaskParam wfTaskParam = (WfTaskParam) JSONObject.toBean(JSONObject.fromObject(params.get("wfTaskParam")), WfTaskParam.class);
        Map<String, Object> variables = wfTaskParam.getVariables();//组装流程参数
        wfTaskParam.setVariables(variables);
        wfTaskParam.setUserVO(user);
        wfTaskParam.setProcessInsName("提示承兌审批人审批");
        fWfTaskService.submitTask(wfTaskParam);
        return true;
    }

    @Override
    public boolean backFlow(Map<String, Object> params) {
        //1.人工登記
        UserVO user = UserUtil.getUser();
        ReceiptBillInfo receiptBillInfo = JSONUtil.toBean(JSONUtil.parseObj(params.get("receiptBillInfo")), ReceiptBillInfo.class);
        receiptBillInfo.setApvst("2");
        receiptBillInfo.setCreateName(user.getStaffName());
        receiptBillInfo.setUpdateName(user.getStaffName());
        receiptBillInfo.setIsBack("1");
        receiptBillInfo.setPreviousInstanceId(receiptBillInfo.getProcessInstanceId());
        if (StringUtils.isNotBlank(receiptBillInfo.getId())) {
            receiptBillInfoMapper.updateById(receiptBillInfo);
        } else {
            receiptBillInfoMapper.insert(receiptBillInfo);
        }
        WfTaskParam wfTaskParam = (WfTaskParam) JSONObject.toBean(JSONObject.fromObject(params.get("wfTaskParam")), WfTaskParam.class);
        wfTaskParam.setUserVO(user);
        wfTaskParam.setProcessInsName(user.getDefaultOrg().getParentOrg().getOrgName() + "出票登记");
        wfTaskParam.setBusinessKey(receiptBillInfo.getId());//业务主键
        wfTaskParam.setApproveNo(receiptBillInfo.getOutBillNumber());//审批编号
        Map<String, Object> variables = wfTaskParam.getBaseParam(user);//组装流程参数
        wfTaskParam.setVariables(variables);
        R r = fWfTaskService.submitTask(wfTaskParam);
        if (!"0".equals(r.get("code").toString())) {
            throw new BusinessException(r.get("msg").toString());
        }
        return true;
    }

    @Override
    public void backAcceptBill(String id, String status, String processInstanceId) {
        QueryWrapper<ReceiptBillInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        ReceiptBillInfo receiptBillInfo = receiptBillInfoMapper.selectOne(queryWrapper);
        if (status.equals(WorkflowContants.PROCESS_STATUS_1)) {
            receiptBillInfo.setProcessInstanceId(processInstanceId);
            receiptBillInfo.setApvst("3");
            receiptBillInfo.setState("0");
            receiptBillInfoMapper.updateById(receiptBillInfo);
        }
        //这里判断是否是开票登记的流程结束
        if (status.equals(WorkflowContants.PROCESS_STATUS_2)) {
            //4本部审批结束
            receiptBillInfo.setApvst("4");
            receiptBillInfo.setState("1");
            receiptBillInfoMapper.updateById(receiptBillInfo);

        }
        if (status.equals(WorkflowContants.PROCESS_STATUS_3)) {
            receiptBillInfo.setApvst("2");
            receiptBillInfo.setIsBack("0");
            receiptBillInfo.setState("1");
            receiptBillInfoMapper.updateById(receiptBillInfo);
        }
    }

    @Override
    public boolean backModifyFlow(Map<String, Object> params, UserVO user) {
        ReceiptBillInfo receiptBillInfo = JSONUtil.toBean(JSONUtil.parseObj(params.get("receiptBillInfo")), ReceiptBillInfo.class);
        if (receiptBillInfo.getId() == null || "".equals(receiptBillInfo.getId())) {
            throw new ResultException(ResultStatus.FAILURE, "获取id失败，id不能为空！");
        }
        receiptBillInfo.setUpdateName(user.getStaffName());
        receiptBillInfoMapper.updateById(receiptBillInfo);
        WfTaskParam wfTaskParam = (WfTaskParam) JSONObject.toBean(JSONObject.fromObject(params.get("wfTaskParam")), WfTaskParam.class);
        Map<String, Object> variables = wfTaskParam.getVariables();//组装流程参数
        wfTaskParam.setVariables(variables);
        wfTaskParam.setUserVO(user);
        wfTaskParam.setProcessInsName("撤销提示承兌审批人审批");
        fWfTaskService.submitTask(wfTaskParam);
        return true;
    }
}
